package com.starbaba.mall.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.jumai.server.common.util.ApplicationProperties;
import com.jumai.server.qiniu.QiniuUploadUtils;
import com.qiniu.common.Zone;
import com.qiniu.storage.Configuration;
import com.starbaba.base.dao.LoanManagerBaseDao;
import com.starbaba.mall.service.MallItemTopicService;
import com.starbaba.mall.service.MallTopicService;
import com.starbaba.redis.JedisUtils;
import com.tuanzi.server.loan_base.constant.LoanRedisKey;
import com.tuanzi.server.loan_base.enums.MallTopicType;
import com.tuanzi.server.loan_base.model.db.Loan_Mall_Item;
import com.tuanzi.server.loan_base.model.db.Loan_Mall_Item_Topic;
import com.tuanzi.server.loan_base.model.db.Loan_Mall_Topic;
import com.tuanzi.server.loan_base.util.DateUtils;

public class MallTopicServiceImpl extends LoanManagerBaseDao implements MallTopicService{

	@Override
	public List<Loan_Mall_Topic> getTopicList(Map<String, Object> paramsMap,
			int pageNo, int pageSize) {
		
		String sql = generateGetTopicListSql(paramsMap) + " LIMIT " + pageNo + "," + pageSize;
		List<Loan_Mall_Topic> list = null;
		try {
			
			list = getDao().list(sql, Loan_Mall_Topic.class);
			
		} catch (AppException e) {
			LogService.error(e);
		}
		return list;
	}

	@Override
	public int countTopic(Map<String, Object> paramsMap) {
		String sql = "SELECT COUNT(1) FROM (" + generateGetTopicListSql(paramsMap) + ") AS a";
		int result = 0;
		try {
			
			result = getDao().getInt(sql);
			
		} catch (AppException e) {
			LogService.error(e);
		}
		return result;
	}

	@Override
	public void addTopic(Map<String, Object> paramsMap) {
		try {
			
			//新增专题
			Loan_Mall_Topic topic = setLoan_Mall_Topic(paramsMap, 0);
			Long topic_id = getDao().addReturnGeneratedKey(topic);
			
			// 更新专题浏览次数缓存
			String people_view_count = (String) paramsMap.get("people_view_count");
			if(StringUtils.isNotEmpty(people_view_count)){
				JedisUtils.set(LoanRedisKey.MALL_TOPIC_VIEW_COUNT + topic_id, people_view_count);
			}
			
			//专题类型不为首页专题：记录专题跳转链接
			String type = (String) paramsMap.get("type");
			if(Integer.parseInt(type) != MallTopicType.INDEX_LIST.getId()){
				String link = ApplicationProperties.get("mall.topic.link") 
						+"&topic_id="+ topic_id + "&type="+ type;
				topic.setId(topic_id);
				topic.setLink(link);
				getDao().update(topic, "id");
			}
			
			//为专题新增商品
			String source_ids = (String) paramsMap.get("source_ids");
			if(StringUtils.isNotEmpty(source_ids)){
				
				String[] sourceIdArray = source_ids.split(",");
				for(int i = 0; i < sourceIdArray.length; i++){
					
					String source_id = sourceIdArray[i];
					
					if(StringUtils.isNotEmpty(source_id)){
						
						Loan_Mall_Item_Topic itemTopic = new Loan_Mall_Item_Topic();
						itemTopic.setTopic_id(topic_id);
						itemTopic.setItem_source_id(source_id);
						itemTopic.setSort_index(i);
						
						//新增前先检查是否已存在记录
						String sql = " SELECT id FROM `loan_mall_item_topic` WHERE `topic_id` = ? AND `item_source_id` = ? ";
						int id = getDao().getInt(sql, topic_id, source_id);
						if(id <= 0){
							getDao().add(itemTopic);
						}
					}
					
					
				}
				
			}
			
			
			
		} catch (AppException e) {
			LogService.error(e);
		}
		
	}

	@Override
	public int updateTopic(Map<String, Object> paramsMap, Long topicId) {
		
		try {
			
			Loan_Mall_Topic topic = setLoan_Mall_Topic(paramsMap, topicId);
			topic.setId(topicId);
			getDao().update(topic, "id");
			
			// 更新专题浏览次数缓存
			String people_view_count = (String) paramsMap.get("people_view_count");
			if(StringUtils.isNotEmpty(people_view_count)){
				JedisUtils.set(LoanRedisKey.MALL_TOPIC_VIEW_COUNT + topicId, people_view_count);
			}
			
			//删除专题下原有的商品
			MallItemTopicService itemTopicService = new MallItemTopicServiceImpl();
			itemTopicService.deleteLoan_Mall_Item(topicId);
			
			//为专题新增商品
			String source_ids = (String) paramsMap.get("source_ids");
			//去掉多余逗号
			if(StringUtils.isNotEmpty(source_ids)){
				
				String[] sourceIdArray = source_ids.split(",");
				for(int i = 0; i < sourceIdArray.length; i++){
					
					String source_id = sourceIdArray[i];
					if(StringUtils.isNotEmpty(source_id)){
						
						Loan_Mall_Item_Topic itemTopic = new Loan_Mall_Item_Topic();
						itemTopic.setTopic_id(topicId);
						itemTopic.setItem_source_id(source_id);
						itemTopic.setSort_index(i);
						
						//新增前先检查是否已存在记录
						String sql = " SELECT id FROM `loan_mall_item_topic` WHERE `topic_id` = ? AND `item_source_id` = ? ";
						int id = getDao().getInt(sql, topicId, source_id);
						if(id <= 0){
							getDao().add(itemTopic);
						}
						
						//getDao().add(itemTopic);
						
					}
					
				}
				
			}
			
		} catch (AppException e) {
			LogService.error(e);
		}
		
		return 0;
	}
	
	@Override
	public int updateTopicStatus(Map<String, Object> paramsMap) {
		
		Object id =  paramsMap.get("id");
		Object status =  paramsMap.get("status");
		String sql = "UPDATE `loan_mall_topic` SET `status` = ? WHERE id = ? ";
		int result = 0;
		try {
			result = getDao().update(sql, status, id);
		} catch (AppException e) {
			LogService.error(e);
		}
		return result;
	}
	
	
	/**
	 * 设置专题model
	 * @param paramsMap 参数
	 * @param topicId 专题id，0代表没有（新增操作）
	 * @return
	 */
	private Loan_Mall_Topic setLoan_Mall_Topic(Map<String, Object> paramsMap, long topicId){
		
		String title = (String) paramsMap.get("title");
		String secondary_title = (String) paramsMap.get("secondary_title");
		String type = (String) paramsMap.get("type");
		String description = (String) paramsMap.get("description");
		String operator = (String) paramsMap.get("operator");
		File img_file = (File) paramsMap.get("img_file");
		File small_img_file = (File) paramsMap.get("small_img_file");
		String link = "-";
		
		if(Integer.parseInt(type) != MallTopicType.INDEX_LIST.getId()){
			link = ApplicationProperties.get("mall.topic.link") 
					+"&topic_id="+ topicId + "&type="+ type;
		}
		
		String img = null;
		String small_img = null;
		
		if(img_file != null){
			try {
				img = QiniuUploadUtils.updateImg("mall_topic", new FileInputStream(img_file), null, new Configuration(Zone.zone0()));
			} catch (Exception e) {
				LogService.error(e);
			}
		}
		
		if(small_img_file != null){
			try {
				small_img = QiniuUploadUtils.updateImg("mall_topic", new FileInputStream(small_img_file), null, new Configuration(Zone.zone0()));
			} catch (Exception e) {
				LogService.error(e);
			}
		}
		
		MallTopicService topicService = new MallTopicServiceImpl();
		int status = 0;
		int sort_index = 0;
		if(topicId == 0){  //新增操作，默认下线状态，位置排在最后面
			
			int maxSortIndex = getmaxTopicSortIndex();
			sort_index = maxSortIndex + 1;
			
		}else{          //更新专题，保持原来的状态、位置不变
			
			Loan_Mall_Topic oldTopic = topicService.getTopic(topicId);
			if(oldTopic != null){
				status = oldTopic.getStatus();
				sort_index = oldTopic.getSort_index();
			}
			
		}
		
		Loan_Mall_Topic topic = new Loan_Mall_Topic();
		topic.setTitle(title.trim());
		if(StringUtils.isNotEmpty(secondary_title)){
			topic.setSecondary_title(secondary_title.trim());
		}
		topic.setType(Integer.parseInt(type));
		topic.setImg(img);
		topic.setSmall_img(small_img);
		topic.setDescription(StringUtils.isNotEmpty(description) ? description.trim() : description);
		topic.setStatus(status);
		topic.setSort_index(sort_index);
		topic.setCtime(DateUtils.getCurrentTime());
		topic.setOperator(operator);
		topic.setLink(link);
		
		return topic;
		
	}
	
	@Override
	public Loan_Mall_Topic getTopic(Long id) {
		
		String sql = "SELECT * FROM `loan_mall_topic` WHERE id = ?";
		Loan_Mall_Topic topic = null;
		try {
			
			topic = getDao().get(sql, Loan_Mall_Topic.class, id);
			
		} catch (AppException e) {
			LogService.error(e);
		}
		
		return topic;
	}

	@Override
	public List<Loan_Mall_Item> getOnlineItemList(Map<String, Object> paramsMap,
			int pageNo, int pageSize) {
		
		String sql = generateGetOnlineItemListSql(paramsMap) + " LIMIT ?,? ";
		
		List<Loan_Mall_Item> list = null;
		try {
			
			list = getDao().list(sql.toString(), Loan_Mall_Item.class, pageNo, pageSize);
			
		} catch (AppException e) {
			LogService.error(e);
		}
		
		return list;
	}

	@Override
	public int countOnlineItem(Map<String, Object> paramsMap) {
		
		String sql = "SELECT COUNT(1) FROM (" + generateGetOnlineItemListSql(paramsMap) + ") AS a";
		int result = 0;
		try {
			
			result = getDao().getInt(sql);
			
		} catch (AppException e) {
			LogService.error(e);
		}
		
		return result;
	}
	

	@Override
	public void sortTab(Map<String, Object> paramsMap) {
		
		String prdidListStr = (String) paramsMap.get("prdSortList");
		String[] prdidList = prdidListStr.split("#");
		String sql = "UPDATE `loan_mall_topic` SET sort_index = ? WHERE id = ? ";
		for (int index = 0; index < prdidList.length; ++index) {
			Long id = Long.parseLong(prdidList[index]);
			try {
				getDao().update(sql, index, id);
			} catch (AppException e) {
				LogService.error(e);
			}
		}
		
	}
	
	/**
	 * 生成查询专题列表sql
	 * @param paramsMap
	 */
	private String generateGetTopicListSql(Map<String, Object> paramsMap){
		
		String title = (String) paramsMap.get("title");
		String status = (String) paramsMap.get("status");
		String type = (String) paramsMap.get("type");
		
		StringBuilder sql = new StringBuilder("SELECT * FROM `loan_mall_topic` WHERE 1 = 1 ");
		if(StringUtils.isNotEmpty(title)){
			sql.append(" AND title = '" + title.trim() + "'");
		}
		
		if(StringUtils.isNotEmpty(status)){
			sql.append(" AND `status` = " + status);
		}
		
		if(StringUtils.isNotEmpty(type)){
			sql.append(" AND `type` = " + type);
		}
		
		sql.append(" ORDER BY sort_index");
		
		return sql.toString();
	}
	
	
	/**
	 * 查询专题的最大位置
	 * @return
	 */
	private int getmaxTopicSortIndex(){
		
		String sql = "SELECT MAX(sort_index) FROM `loan_mall_topic` ";
		int maxSortIndex = 0;
		try {
			 maxSortIndex = getDao().getInt(sql);
		} catch (AppException e) {
			LogService.error(e);
		}
		return maxSortIndex;
		
	}

	/**
	 * 生成查询在线商品列表sql
	 * @param paramsMap
	 * @return
	 */
	private String generateGetOnlineItemListSql(Map<String, Object> paramsMap){
		
		String title = (String)paramsMap.get("title");
		String isCouponItem = (String)paramsMap.get("is_coupon_item");
		StringBuilder sql = new StringBuilder("SELECT * FROM `loan_mall_item` WHERE source_status = 1 AND status = 1 ");  //只查上线状态的商品
		if(StringUtils.isNotEmpty(title)){
			sql.append(" AND `title` LIKE  '%" + title + "%'");
		}
		if(StringUtils.isNotEmpty(isCouponItem)){
			sql.append(" AND `is_coupon_item` = " + isCouponItem);
		}
		return sql.toString();
	}

}
